<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="货品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入货品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="货品编号" prop="productCode">
        <el-input
          v-model="queryParams.productCode"
          placeholder="请输入货品编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="货品类型" prop="productTypeCode">
        <div>
      <el-select v-model="queryParams.productTypeCode" placeholder="请选择">
      <el-option
        v-for="item in selectOptions"
        :key="item.productTypeCode"
        :label="item.fullPathName"
        :value="item.productTypeCode"
      />
    </el-select>
  </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:product:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:product:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:product:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['product:product:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="" >
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="货品名称" align="center" prop="productName" />
      <el-table-column label="状态" align="center" prop="productStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.py_product_type" :value="scope.row.productStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="货品编号" align="center" prop="productCode" >
        <template slot-scope="scope">
          <router-link :to="`/wms/product/product/productDetail/${scope.row.productId}`" tag="span" style="color: blue; cursor: pointer;">
            {{ scope.row.productCode }}
          </router-link>
        </template>
      </el-table-column>
      <el-table-column label="货品类型" align="center" prop="productTypeList[0].productTypeName" />
      <el-table-column label="规格型号" align="center" prop="productModel" />
      <el-table-column label="单位" align="center" prop="productUnit">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.py_product_unit" :value="scope.row.productUnit"/>
        </template>
      </el-table-column>
      <el-table-column label="供应商" align="center" prop="pySuppliersList[0].supplierName" />
      <el-table-column label="入库参考价" align="center" prop="inboundPrice" />
      <el-table-column label="出库参考价" align="center" prop="outboundPrice" />
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="预警天数" align="center" prop="warningDays" />
    <el-table-column label="操作人" align="center" prop="createBy" />
      <el-table-column label="操作时间" align="center" >
        <template #default="scope">
          {{formatDateTime(scope.row.createTime)}}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:product:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:product:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改货品信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="货品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入货品名称" />
        </el-form-item>
        <el-form-item label="状态" prop="productStatus">
          <el-select v-model="form.productStatus" placeholder="请选择状态">
            <el-option
              v-for="dict in dict.type.py_product_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="货品编号" prop="productCode">
          <el-input v-model="form.productCode" placeholder="请输入货品编号" readonly />
        </el-form-item>
       <el-form-item label="货品类型" prop="productType">
        <div>
    <el-select v-model="form.productType" placeholder="请选择">
      <el-option
        v-for="item in selectOptions"
        :key="item.productTypeCode"
        :label="item.fullPathName"
        :value="item.productTypeCode"
      />
    </el-select>
  </div>
      </el-form-item>
        <el-form-item label="规格型号" prop="productModel">
          <el-input v-model="form.productModel" placeholder="请输入规格型号" />
        </el-form-item>
        <el-form-item label="单位" prop="productUnit">
          <el-select v-model="form.productUnit" placeholder="请选择单位">
            <el-option
              v-for="dict in dict.type.py_product_unit"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="productSupplier">
          <el-select v-model="form.productSupplier" placeholder="请输入供应商">
            <el-option
              :key="item.supplierId"
              v-for="item in suppliers"
              :label="item.pySuppliersList[0].supplierName"
              :value="item.pySuppliersList[0].supplierId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入库参考价" prop="inboundPrice">
          <el-input v-model="form.inboundPrice" placeholder="请输入入库参考价" />
        </el-form-item>
        <el-form-item label="出库参考价" prop="outboundPrice">
          <el-input v-model="form.outboundPrice" placeholder="请输入出库参考价" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序" />
        </el-form-item>

          <el-form-item label="保质期管理" prop="isEnable">
          <el-radio-group v-model="form.isEnable">
            <el-radio
              v-for="dict in dict.type.is_enable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
          </el-form-item>
          <el-form-item label="保质期单位" v-if="this.form.isEnable=='1'">
              <el-form-item prop="shelfLifeDays" >
                <el-input  v-model="form.shelfLifeDays" placeholder="请输入" style="width: 80px" />
               </el-form-item>
               <el-form-item prop="shelfLifeUnit" >
              <el-select v-model="form.shelfLifeUnit" placeholder="请选择" class="yang">
            <el-option
              v-for="dict in dict.type.shelf_life_days"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
          </el-form-item>

        </el-form-item>



        <el-form-item label="预警天数" prop="warningDays"  v-if="this.form.isEnable=='1'">
          <el-input v-model="form.warningDays" placeholder="请输入预警天数" />
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <image-upload v-model="form.image"/>
        </el-form-item>
        <el-form-item label="备注" prop="productRemark">
          <el-input v-model="form.productRemark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" >确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct,getCode,selectPySuppliers} from "@/api/product/product";
import moment from "moment";
import { findSelect } from "@/api/product/type";


export default {
  name: "Product",
  dicts: ['is_enable', 'shelf_life_days', 'py_product_type', 'py_suppliers_status', 'py_product_unit'],
  data() {
    return {
      productType: '',
      selectOptions: [],
      checkboxValue: true,  // 控制文本框显示的状态
      //供货商下拉列表
      suppliers:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedPySuppliers: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 货品信息表格数据
      productList: [],
      // 供应商信息表格数据
      pySuppliersList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        productTypeCode: null,
      },
      // 表单参数
      form: {},

      // 表单校验
      rules: {
        productName: [
          { required: true, message: "货品名称不能为空", trigger: "blur" }
        ],
        productStatus: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        productCode: [
          { required: true, message: "货品编号不能为空", trigger: "blur" }
        ],
        productTypeCode: [
          { required: true, message: "货品类型不能为空", trigger: "blur" }
        ],
        productModel: [
          { required: true, message: "规格型号不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.fetchItems();

  },
  computed: {
    isEnableVisible() {
      return this.form.isEnable=='1';
    }
  },
  methods: {
    /** 查询货品信息列表 */
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      // 获取供应商下拉框
       selectPySuppliers().then(response => {
        this.suppliers= response;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        productTypeCode:null,
        productId: null,
        productName: null,
        productStatus: null,
        productCode: null,
        productType: null,
        isEnable: null,
        productModel: null,
        productUnit: null,
        productSupplier: null,
        inboundPrice: null,
        outboundPrice: null,
        sort: null,
        shelfLifeDays: null,
        shelfLifeUnit: null,
        warningDays: null,
        image: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        productRemark: null,
        isDelete: null
      };
      this.pySuppliersList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加货品信息";

 /** 获取编号*/
      getCode(1).then(response => {
        console.log(response);
        this.form.productCode=response.sequence;
        this.form.number=response.number;
        this.form.codeId=response.codeId;
    });

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const productId = row.productId || this.ids
      getProduct(productId).then(response => {
        this.form = response.data;
        this.form.isEnable = response.data.isEnable;
        this.open = true;
        this.title = "修改货品信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.isEnable = this.form.isEnable;
          this.form.pySuppliersList = this.pySuppliersList;

          if (this.form.productId != null) {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const productIds = row.productId || this.ids;
      if (row.productStatus == 1) {
        this.$modal.msgError("已启用的货品信息不能删除");
        return;
      } else {
        this.$modal.confirm('是否确认删除货品信息编号为"' + productIds + '"的数据项？').then(function() {
        return delProduct(productIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});

      }
    },
	/** 供应商信息序号 */
    rowPySuppliersIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 供应商信息添加按钮操作 */
    handleAddPySuppliers() {
      let obj = {};
      obj.supplierCode = "";
      obj.industryId = "";
      obj.supplierCategoryId = "";
      obj.contactPerson = "";
      obj.contactPhone = "";
      obj.email = "";
      obj.purchaseDepartmentId = "";
      obj.purchaseResponsibleId = "";
      obj.status = "";
      obj.supplierAddress = "";
      obj.remarks = "";
      obj.manager = "";
      obj.createdAt = "";
      obj.updatedAt = "";
      obj.isDeleted = "";
      obj.supplierName = "";
      this.pySuppliersList.push(obj);
    },
    /** 供应商信息删除按钮操作 */
    handleDeletePySuppliers() {
      if (this.checkedPySuppliers.length == 0) {
        this.$modal.msgError("请先选择要删除的供应商信息数据");
      } else {
        const pySuppliersList = this.pySuppliersList;
        const checkedPySuppliers = this.checkedPySuppliers;
        this.pySuppliersList = pySuppliersList.filter(function(item) {
          return checkedPySuppliers.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handlePySuppliersSelectionChange(selection) {
      this.checkedPySuppliers = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('product/product/export', {
        ...this.queryParams
      }, `product_${new Date().getTime()}.xlsx`)
    },
     /**
     * 时间转换
     */
    formatDateTime(date){
      return moment(date).format("YYYY-MM-DD");
    },
      async fetchItems() {
      try {
        const response = await findSelect();
        console.log('Response from findSelect:', response);
        if (Array.isArray(response)) {
          this.selectOptions = await this.convertToSelectOptions(response);
          console.log('Converted selectOptions:', this.selectOptions);
        } else {
          console.error('Expected an array, but got:', response);
        }
      } catch (error) {
        console.error('Error fetching items:', error);
      }
    },
    async convertToSelectOptions(data) {
      if (!Array.isArray(data)) {
        console.error('Expected an array, but got:', data);
        return [];
      }

      // 创建一个映射，用于快速查找父项
      const itemMap = new Map(data.map(item => [item.productTypeCode, item]));
      // 创建一个数组，用于存储所有项
      const allItems = [];

      data.forEach(async (item) => {
        allItems.push(await this.createSelectOption(item, itemMap));
      });

      return allItems;
    },
    async createSelectOption(item, itemMap) {
      const fullPathName = await this.getFullPathName(item, itemMap);
      return {
        productTypeCode: item.productTypeCode,
        productTypeName: item.productTypeName,
        fullPathName: fullPathName
      };
    },
    async getFullPathName(item, itemMap) {
      let pathName = item.productTypeName;
      let currentItem = item;

      while (currentItem.parentId !== null) {
        const parentItem = itemMap.get(currentItem.parentId);
        if (parentItem) {
          pathName = `${parentItem.productTypeName} / ${pathName}`;
          currentItem = parentItem;
        } else {
          break;
        }
      }

      return pathName;
    }
  }
};
</script>

<style scoped>
.yang{
  width: 100px;
  margin-left: 10px;
}

select {
  width: 100%;
  padding: 8px;
  margin-top: 5px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
}

option {
  padding: 5px;
}
</style>
